
import datolib.*;
import java.net.*;
import java.util.*;
import java.io.*;

public class SessionConnector implements Runnable {
	
	private Socket socket;
	
	public SessionConnector(Socket s) {
		this.socket = s;
	}	
	
	
	public void run() {
		
		try {
			
			TcpGateway socket = new TcpGateway(this.socket);
		
			
			
			XmlMessage message = socket.readNextMessage();
			
			if (!message.isLAP()) {
				 return;
			} 
			
			
			LapMessage lap = message.toLap();
			
			
			if (!DatoliteServer.hasApplication(lap.application())) {
				socket.afl("\"" + lap.application() + "\" not found");
				return;
			}		
			
			
			DatoliteApplication app = DatoliteServer.getApplication(lap.application());
					
					
			if (!app.checkCredentials(lap.username(), lap.password())) {
				socket.afl("username or password incorrect");
				return;
			}
			
		
			
			DatoliteInstance instance = app.makeInstance(lap.platform());
			
			if (instance == null) {
				System.out.println("Failed to make instance");
				return;
			}
			
			
			TcpSession session = new TcpSession(socket, instance);
							
			File f = new File(instance.getUipFile());
			int length = (int)f.length();
							
			socket.asl(length, instance.getCimlFile());
			
			session.run();					
		
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
}
